package cn.hutool.captcha;

import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.captcha.generator.RandomGenerator;
import org.junit.Before;
import org.junit.Test;

import java.io.File;

import static org.assertj.core.api.Assertions.assertThat;

public class CaptchaTest {
    @Before
    public void before() {
        new File("target").mkdirs();
    }

    @Test
    public void testLineCaptcha() {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);

        //图形验证码写出，可以写出到文件，也可以写出到流
        lineCaptcha.write(new File("target/line1.png"));
        //验证图形验证码的有效性，返回boolean值
        assertThat(lineCaptcha.verify(lineCaptcha.getCode())).isTrue();

        //重新生成验证码
        lineCaptcha.createCode();
        lineCaptcha.write(new File("target/line2.png"));
        //新的验证码
        assertThat(lineCaptcha.verify(lineCaptcha.getCode())).isTrue();
    }

    @Test
    public void testCircleCaptcha() {
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        //CircleCaptcha captcha = new CircleCaptcha(200, 100, 4, 20);
        //图形验证码写出，可以写出到文件，也可以写出到流
        captcha.write(new File("target/circle.png"));
        //验证图形验证码的有效性，返回boolean值
        assertThat(captcha.verify(captcha.getCode())).isTrue();
    }

    @Test
    public void testShearCaptcha() {
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 100, 4, 4);
        //ShearCaptcha captcha = new ShearCaptcha(200, 100, 4, 4);
        //图形验证码写出，可以写出到文件，也可以写出到流
        captcha.write(new File("target/shear.png"));
        //验证图形验证码的有效性，返回boolean值
        assertThat(captcha.verify(captcha.getCode())).isTrue();
    }

    @Test
    public void testGifCaptcha() {
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        GifCaptcha captcha = CaptchaUtil.createGifCaptcha(200, 100);
        //ShearCaptcha captcha = new ShearCaptcha(200, 100, 4, 4);
        //图形验证码写出，可以写出到文件，也可以写出到流
        captcha.write(new File("target/gif.gif"));
        //验证图形验证码的有效性，返回boolean值
        assertThat(captcha.verify(captcha.getCode())).isTrue();
    }

    @Test
    public void testCustomer() {
        // 自定义纯数字的验证码（随机4位数字，可重复）
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        lineCaptcha.setGenerator(randomGenerator);
        // 重新生成code
        lineCaptcha.createCode();
        lineCaptcha.write(new File("target/customer1.png"));
        assertThat(lineCaptcha.verify(lineCaptcha.getCode())).isTrue();

        MathGenerator generator = new MathGenerator();
        lineCaptcha.setGenerator(generator);
        lineCaptcha.createCode();
        lineCaptcha.write(new File("target/customer2.png"));
        System.out.println(lineCaptcha.getCode());
        assertThat(generator.verify("95-57=", "38")).isTrue();
    }
}
